<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->

<head>
    <meta charset="utf-8" />
    <title></title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />
    <meta http-equiv="Access-Control-Allow-Origin" content="*" />
    <!-- Bootstrap 3.3.6 -->
    <link rel="stylesheet" href="https://tv.speechb.com/lib/superui/content/ui/global/bootstrap/css/bootstrap.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="https://tv.speechb.com/lib/superui/content/adminlte/dist/css/AdminLTE.css">
    <link rel="stylesheet" href="https://tv.speechb.com/lib/superui/content/adminlte/dist/css/skins/_all-skins.min.css">
    <link href="https://tv.speechb.com/lib/superui/content/min/css/supershopui.common.min.css" rel="stylesheet" />
    <link href="https://tv.speechb.com/lib/superui/content/plugins/bootstrap-table/bootstrap-table.css" rel="stylesheet" />
    <link href="https://tv.speechb.com/lib/superui/content/layx/layx.min.css" rel="stylesheet" />
    <link href="https://tv.speechb.com/lib/x-editable/css/bootstrap-editable.css" rel="stylesheet"/>
    <link href="https://tv.speechb.com/lib/x-editable/css/select2-bootstrap.css" rel="stylesheet"/>
    <link href="https://tv.speechb.com/lib/layui/css/layui.css" rel="stylesheet"/>
    <!--全局通用框架样式 end-->
</head>
<body>

<!-- Main content -->
<section class="content">

    <div class="row">
        <!-- BEGIN SAMPLE TABLE PORTLET-->
        <div class="col-md-12">


            <div id="toolbar" class="btn-group">
                <button id="btn_add" type="button" class="btn btn-default">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                </button>
                <button id="btn_delete" type="button" class="btn btn-default">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                </button>
            </div>
            <div class="table-scrollable">
                <table id="table"></table>

            </div>
        </div>
    </div>

</section>
<script src="http://tv.speechb.com/lib/superui/content/ui/global/jQuery/jquery.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="https://tv.speechb.com/lib/superui/content/ui/global/bootstrap/js/bootstrap.min.js"></script>

<script src="https://tv.speechb.com/lib/x-editable/js/bootstrap-editable.min.js"></script>

<script src="https://tv.speechb.com/lib/superui/content/min/js/supershopui.common.js"></script>
<script src="https://tv.speechb.com/lib/superui/content/plugins/bootstrap-table/bootstrap-table.js"></script>
<script src="https://tv.speechb.com/lib/superui/content/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
<script src="https://tv.speechb.com/lib/superui/content/layx/layx.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://tv.speechb.com/lib/toaster/jquery.toaster.js"></script>
<script type="text/javascript" charset="utf-8" src="https://tv.speechb.com/lib/layui/layui.js"></script>
</body>
<script>

    $(function () {
        $('#table').bootstrapTable({
            url: '/admin/speechcraft',         //请求后台的URL（*）
            method: 'GET',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortOrder: "desc",                   //排序方式

            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            // clickToSelect: true,                //是否启用点击选中行
            height: 'auto',                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "id",

            rowStyle:rowStyle,//通过自定义函数设置行样式
            //得到查询的参数
                     queryParams : function (params) {
                         //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
                        var temp = {
                            page_size: params.limit,                         //页面大小
                            page_num: (params.offset / params.limit) + 1,   //页码
                             sort: params.sort,      //排序列名
                            order: params.order, //排位命令（desc，asc）
                            search: params.search
                        };
                        return temp;
                     },
            columns: [{
                checkbox: true
            },{
                field:'id',
                title: 'ID',
                visible: false
            },{
                field:'sorting',
                title: '序号',
                align: 'center',
                sortable: true,//启用排序
                width:60,
                formatter: function (value, row, index) {
                    var pageSize = $('#table').bootstrapTable('getOptions').pageSize;     //通过table的#id 得到每页多少条
                    var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber; //通过table的#id 得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;    // 返回每条的序号： 每页条数 *（当前页 - 1 ）+ 序号
                }
            }, {
                field: 'title',
                title: '分类',
                align: 'center',
                width:120,
            }, {
                field: 'content',
                title: '话术内容',
                width:280,
                formatter:function(value,row,index) {
                    return '<a id="content' + row.id + '"data-type="textarea" value="'+row.id+'">'+value+'</a>';
                }
            }, {
                field: 'name',
                title: '用户名',
                align: 'center',
                width:80,
            }, {
                field: 'post_type_id',
                title: '发布类型',
                align: 'center',
                width:100,
                formatter:publishTypeFormatter
            }, {
                field: 'update_time',
                title: '更新日期',
                align: 'center',
                width:160,
            },{
                field: 'status_id',
                title: '状态',
                align: 'center',
                width:70,
                formatter:stateFormatter
            },{
                field: 'operation',
                title: '操作',
                align: 'center',
                width:120,
                events:actionEvents,//给按钮注册事件
                formatter:actionFormatter//表格中增加按钮
            }],
            onLoadSuccess: function (data) {
                autoHeightTable();
                console.log(data);
                for(var i=0;i<data.rows.length;i++) {
                    console.log("#content"+data.rows[i].id);
                    $("#content"+data.rows[i].id).editable({
                       type:'textarea',
                        pk:data.rows[i].id ,
                        url:'/admin/speechcraft/update_content',
                        title:'话术内容编辑',
                        placement:'right',
                        rows:8,
                        success:function(rspData,newValue) {
                           // 有返回既有错误
                           if(rspData.code<0) {
                               return rspData.data;
                           }
                        }
                    });

                    // 状态可编辑
                    $('#status'+data.rows[i].id).editable({
                        type:'select',
                        pk:data.rows[i].id ,
                        url:'/admin/speechcraft/update_status',
                        title:'话术发布状态编辑',
                        value: data.rows[i].status_id,
                        placement:'left',
                        source: [
                            {value: 1, text: '普通'},
                            {value: 2, text: 'VIP'},
                            {value: 0, text: '待审核'},
                            {value: -1, text: '未通过'},
                        ],
                        success:function(rspData,newValue) {
                            // 有返回既有错误
                            if(rspData.code<0) {
                                return rspData.data;
                            }
                        }
                    });
                }
            },
            onLoadError: function () {
                showTips("数据加载失败！");
            },
            onClickCell: function(field, value, row, $element) {
                if(field == 'operation' || field == "content" || field == "status_id") {
                   // 操作点击 删除编辑
                } else {
                    console.log(field);
                    console.log(value);
                    console.log(row);
                }
            }
        });

        function autoHeightTable() {
            //设置bootstrapTable起始的高度
            $('#table').bootstrapTable({height:$(window).height()-120});
            //当表格内容的高度小于外面容器的高度，容器的高度设置为内容的高度，相反时容器设置为窗口的高度-160
            if($(".fixed-table-body table").height()<$(".fixed-table-container").height()){
                $(".fixed-table-container").css({"padding-bottom":"0px",height:$(".fixed-table-body table").height()+20});
                // 是当内容少时，使用搜索功能高度保持不变
                $('#table').bootstrapTable('resetView',{height:"auto"});
            }else{
                $(".fixed-table-container").css({height:$(window).height()-150});
            }
        }

        // create event
        $('.create').click(function () {
            showModal($(this).text());
        });

        $("#btn_add").click(function(){
           layx.iframe('speechcraft_publish','发布话术','/static/speechcraft_publish.html');
        });
        $("#btn_delete").click(function(){
            // 批量删除
            var selectRow = $('#table').bootstrapTable('getSelections');
            if (selectRow.length < 1) {
                $.toaster({ priority : "warning", title : "通知", message : "内容未选中！" });
                return false;
            }
            var ids = new Array();
            for(var i=0;i<selectRow.length;i++){
                ids[i]=selectRow[i].id;
            }
            if (confirm('是否批量删除话术?')) {
                $.ajax({
                    url: "/admin/speechcraft/delete_list",
                    type: 'delete',
                    data : {
                        "ids":ids,
                    },
                    success: function (data) {
                        console.log(data.code);
                        if(data.code == 1) {
                            $('#table').bootstrapTable('refresh');
                        } else {
                            $.toaster({ priority : "danger", title : "通知", message : "批量删除话术失败!" });
                        }
                    },
                    error: function () {
                        $.toaster({ priority : "danger", title : "通知", message : "批量删除话术失败!" });
                    }
                })
            }
        });


    });
    function actionFormatter(value) {
        return [
            ' <a href="javascript:;" class="btn btn-icon-only purple update "><i class="fa fa-edit "></i></a>'+
            '<a href="javascript:;" class="btn btn-icon-only red remove"> <i class="fa fa-times "></i></a>',
        ].join('');
    }
    function publishTypeFormatter(value, row) {
        if (row.post_type_id == "1") {
            return ' <span > 官方发布 </span>';
        }
        else if (row.post_type_id == "2") {
            return ' <span style="color:lightseagreen"> 用户发布 </span>';
        }
        else {
            return '<span class="label label-sm label-danger"> 其它 </span>';
        }
    }

    function stateFormatter(value, row) {

        if (row.status_id == "1") {
            return ' <span id="status'+row.id+'" class="label label-sm label-success"> 普通 </span>';
        } else if(row.status_id == "2") {
            return ' <span id="status'+row.id+'" class="label label-sm label-success"> VIP </span>';
        } else if (row.status_id == "0") {
            return ' <span id="status'+row.id+'" class="label label-sm label-warning"> 待审核 </span>';
        }
        else {
            return '<span id="status'+row.id+'" class="label label-sm label-danger"> 未通过 </span>';
        }

    }
    function rowStyle(row, index) {
        var classes = ['active', 'success', 'info', 'warning', 'danger'];

        if (index % 2 === 0 && index / 2 < classes.length) {
            return {
                classes: classes[index / 2]
            };
        }
        return {};
    }
    // update and delete events
    window.actionEvents = {
        'click .update': function (e, value, row) {
            console.log("点击了");

        },
        'click .update': function (e, value, row, index) {
            layx.iframe('speechcraft_publish','发布话术','/static/speechcraft_publish.html?id='+row.id);
        },

        'click .remove': function (e, value, row) {
            if (confirm('是否删除话术?')) {
                $.ajax({
                    url: "/admin/speechcraft/delete?id="+row.id,
                    type: 'delete',
                    success: function (data) {
                            console.log(data.code);
                            if(data.code == 1) {
                                $('#table').bootstrapTable('refresh');
                            } else {
                                $.toaster({ priority : "danger", title : "通知", message : "删除话术失败!" });
                            }
                    },
                    error: function () {
                        $.toaster({ priority : "danger", title : "通知", message : "删除话术失败!" });
                    }
                })
            }
        }
    };

</script>
</html>